#!/bin/bash
#
#######################################
###### Директорія Рубі додатка ########
ruby_dir=/home/kandpco/kandp/
ups_dir=/home/kandpco/kandp/
#pid_tmp=$ups_dir/pid_tmp
#######################################
pid=`cat ${ruby_dir}/log/mongrel.pid`
instance_count=`ps $pid | grep mongrel |  wc -l`
#port=12052
#ps f -u dvernet | grep '\-p $port' | awk {'print $1'} > $pid_tmp
#pidd=`cat $pid_tmp`
#echo ======================
#cat $pid_tmp
########################################
###### Функція Старту Монгрела #########
cd $ruby_dir
start_ruby="/usr/bin/ruby /usr/bin/mongrel_rails start -p 12039 -d -e production -P ${ruby_dir}/log/mongrel.pid"
########################################
###### Лог обробки скрипта #############
flog="/home/kandpco/cron-debug.log"

if [ -e "${ruby_dir}/log/mongrel.pid"  ]; then
	fpid=1
else
	fpid=0
fi
#echo "file_pid=$fpid"
#echo "Proces=$instance_count"

if [  "0" = "$instance_count"  -a  "0" = "$fpid"  ]; then
        echo "Proces=0; file_pid=0" >> $flog && cd $ruby_dir && $start_ruby
fi

if [  "0" = "$instance_count"  -a  "1" = "$fpid"  ]; then
        echo "Proces=0; file_pid=1" >> $flog && cd $ruby_dir && rm -f "log/mongrel.pid" && $start_ruby
fi

#if [  "1" = "$instance_count"  -a  "0" = "$fpid"  ]; then
#        echo "Proces=1; file_pid=0" >> $flog && cd $ruby_dir && kill -9 `$pidd` && $start_ruby
#fi

if [  "1" = "$instance_count"  -a  "1" = "$fpid"  ]; then
        echo "`date` Ruby work correct" >> $flog
fi
